package internal.sitemesh;

import internal.web.PageResponseWrapper;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 用来更简单的控制页面拦截器
 * @author GL
 * @since 2008-4-2 下午12:28:48
 */
public class Sitemesh {
	PageRequestWrapper requestWrapper;
	PageResponseWrapper responseWrapper;
	HttpServletRequest request;
	HttpServletResponse response;
	/**
	 * 构造一个页面拦截器
	 * @param request
	 * @param response
	 */
	public Sitemesh(HttpServletRequest request,HttpServletResponse response) {
		super();
		this.request = request;
		this.response = response;
		this.requestWrapper = new PageRequestWrapper(request){
			
		};
		this.responseWrapper = new PageResponseWrapper(response){
			/* (non-Javadoc)
			 * @see mice.mvc.sitemesh.PageResponseWrapper#setContentType(java.lang.String)
			 */
			@Override
			public void setContentType(String type) {
				if(!type.matches("text/html")){
					deactivateSiteMesh();
					getResponse().setContentType(type);
				}
				super.setContentType(type);
			}
		};
	}
	
	public void activeSitemesh(String encoding){
		responseWrapper.activateSiteMesh("text/html", encoding);
	}
	
	public void chain(FilterChain chain) throws IOException, ServletException{
		chain.doFilter(requestWrapper, responseWrapper);
	}
	
	/**
	 * 拦截中
	 * @return
	 */
	public boolean isWrapping(){
		return responseWrapper.isWrapping();
	}
//	
//	public Source getSource() throws IOException{
//		char[] contents = responseWrapper.getContents();
//		if(contents!=null){
//			return new Source(new CharArrayReader(contents));
//		}
//		return null;
//	}
//	
//	public OutputDocument getDocument() throws IOException{
//		return new OutputDocument(getSource());
//	}
	
	/**
	 * @return the responseWrapper
	 */
	public PageResponseWrapper getResponseWrapper() {
		return responseWrapper;
	}
	
	public char[] getContent() throws IOException{
		return responseWrapper.getContents();
	}
//	
//	public void response(OutputDocument document) throws IOException{
//		document.writeTo(response.getWriter());
//	}
}
